import React from "react";
import Confirm from '../../../common/Confirm'
import Select_common from '../../../common/Select'
import {message,Select,Button,Input} from 'antd';
const Option = Select.Option;
import InputBox from '../../../common/InputBox'
import PackTradeApply from './PackTradeApply'
import Relay from "react-relay";
import GetParentOrderMutation from "../mutation/GetParentOrderMutation";
import GetOrderByTraffickerMutation from "./mutation/GetOrderByTraffickerMutation";
import GetEnterpriseListMutation from "../mutation/GetEnterpriseListMutation"
import FindUsersByEnterpriseIdAndPidMutation from "../mutation/FindUsersByEnterpriseIdAndPidMutation"
import DetailUploadModal from "./DetailUploadModal"
import ReactKey from "../../../util/ReactKey"
import Util from "../../../util/Util"
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation"
import '../css/IndentManage.css'

export default class CreatOrderThree extends React.Component{
    constructor(props){
        super(props);
        this.state={
            oders:[],
            partAordlist:[],
            enterpriseList:[],
            linkman:[],
            instructions:[],
            fristchose:"",
            traderName:"",
            traderUser:"",
            traderId:"",
            dataSource_require:[
                {type:"quality",title:"质量要求",content:""},
                {type:"package",title:"包装要求",content:""},
                {type:"logistics",title:"物流要求",content:""},
                {type:"payMode",title:"付款方式",content:""},
                {type:"dutyBreak",title:"违约责任",content:""},
                {type:"checkAsk",title:"验收要求",content:""},
                ],
        };
        this.instructions=[];
        this.odersobj={};
        this.fristchose = '';
        this.enterpriseList = [{text:"请选择客户",value:"0"}]
        this.enterprisedeobj={};
        this.linkman = [{text:'请选择联系人',value:'0'}];
        this.serviceType = sessionStorage.getItem('serviceType');

    }

    componentWillMount(){
        /*附件赋值*/
        if(this.props.fromEdit== "edit"){
            this.setState({
                instructions:this.props.instructions||[],
                traderName:this.props.traderName||"",
                traderUser:this.props.traderUser||"",
                traderId:this.props.traderId||"",
            });
            this.instructions = this.props.instructions||[]
        }

        this.ispartA = this.props.ispartA;
        if(this.ispartA){
            /*成衣订单*/
            console.log(123);
            /* this.setState({
                traderName:this.props.traderName,
                traderUser:this.props.traderUser,
                traderId:this.props.traderId,
            });*/

            /*Relay.Store.commitUpdate(
                new GetEnterpriseListMutation({
                    entype : '1'
                }),
                {
                    onFailure: () => {

                    },
                    onSuccess: (response) => {
                        let errorCode = response.getEnterpriseList.data.errorCode;
                        if(errorCode == 0){
                            let enterpriseList = response.getEnterpriseList.data.enterpriseList;
                            enterpriseList.map((context,index)=>{
                                this.enterpriseList.push({text:context.enterpriseName,value:context.enterpriseId});
                                this.enterprisedeobj[context.enterpriseId] = {"address":context.address,"enterpriseName":context.enterpriseName}
                            });
                            this.setState({
                                enterpriseList : this.enterpriseList,
                                linkman:this.linkman
                            });
                        }
                    }
                }
            )*/
        }else{
            /*贸易商创建布料辅料订单关联*/
            if(this.serviceType == 6){
                /*贸易商-创建布料、辅料订单*/
                Relay.Store.commitUpdate(
                    new GetOrderByTraffickerMutation({
                        enId : this.props.enterpriseId
                    }),
                    {
                        onFailure: () => {

                        },
                        onSuccess: (response) => {
                            let errorCode = response.getOrderByTrafficker.getOrderByTrafficker.errorCode;
                            if(errorCode==0){
                                let orders = response.getOrderByTrafficker.getOrderByTrafficker.orders;
                                let partAordlist = [];
                                orders.map((context,index)=>{
                                    if(index==0){
                                        if(this.props.fromEdit== "edit"){
                                            this.fristchose = this.props.parentId;
                                        }else {
                                            this.fristchose = context.oid
                                        }
                                    }
                                    partAordlist.push({text:context.oid,value:context.oid});
                                    this.odersobj[context.oid] = {'partAName':context.partAName,'partBName':context.partBName,'account':context.account}
                                });
                                this.setState({
                                    partAordlist:partAordlist,
                                    fristchose:this.fristchose,
                                },()=>{
                                    this.choseorder(this.fristchose);
                                });
                            }
                        }
                    }
                )
            }else {
                Relay.Store.commitUpdate(
                    new GetParentOrderMutation({
                        enId : this.props.enterpriseId
                    }),
                    {
                        onFailure: () => {

                        },
                        onSuccess: (response) => {
                            let errorCode = response.getParentOrder.getParentOrder.errorCode;
                            if(errorCode==0){
                                let orders = response.getParentOrder.getParentOrder.orders;
                                let partAordlist = [];
                                orders.map((context,index)=>{
                                    if(index==0){
                                        if(this.props.fromEdit== "edit"){
                                            this.fristchose = this.props.parentId;
                                        }else {
                                            this.fristchose = context.oid
                                        }
                                    }
                                    partAordlist.push({text:context.oid,value:context.oid});
                                    this.odersobj[context.oid] = {'partAName':context.partAName,'account':context.account}
                                });
                                this.setState({
                                    partAordlist:partAordlist,
                                    fristchose:this.fristchose,
                                },()=>{
                                    this.choseorder(this.fristchose);
                                });
                            }
                        }
                    }
                )
            }
        }
    }
    componentDidMount(){
        /*备注赋值*/
        if(this.props.fromEdit== "edit"){
            this.refs.remarkinput.setState({
                text:this.props.rmark||''
            });
        }
    }
    attach(){
        return  this.state.instructions.map((item,index)=>{
            return(
                <PackTradeApply  key={ReactKey.key} item={item} delqiniufile={this.delqiniufile.bind(this)}/>
            );

        })
    }


    choseorder(oid){
        let partAName;
        let partBName;
        let account;
        if(oid != ''){
            partAName = this.odersobj[oid].partAName;
            partBName = this.odersobj[oid].partBName;
            let accounttext = this.odersobj[oid].account;
            account = Number(accounttext)/100
        }
        if(this.serviceType == 6){
            this.refs.partA.setState({
                text:partBName||''
            });
        }else {
            this.refs.partA.setState({
                text:partAName||''
            });
        }
        this.refs.partacount.setState({
            text:account
        });
    }

    choseem(id){
        if(id ==0){
            this.linkman = [{text:'请选择联系人',value:'0'}];
            this.setState({
                linkman:this.linkman
            });
            this.refs.emaddres.setState({
                text:''
            });
            return;
        }
        let address = this.enterprisedeobj[id].address;
        this.refs.emaddres.setState({
            text:address||''  
        });
        this.linkman = [{text:'请选择联系人',value:'0'}];
        Relay.Store.commitUpdate(
            new FindUsersByEnterpriseIdAndPidMutation({
                enterpriseId : id,
                /*销售订单管理权限的用户*/
                pid:'11'
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {

                    let errorCode = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.errorCode;
                    if(errorCode=="0"){
                        let userModelList = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.userModelList;

                        userModelList.map((context,index)=>{
                            this.linkman.push({text:context.name+" "+context.phone,value:context.uid})
                        });
                        this.setState({
                            linkman:this.linkman
                        });
                    }
                }
            }
        )
    }

    addinstructions(){
        this.props.addinstructions();
    }

    addpact(name,hash,url,fileKey,sid){
        this.instructions.push({"name":name,"hash":hash,"url":url,"fileKey":fileKey,"sid":sid});
        this.setState({
            instructions:this.instructions
        });
    }

    delqiniufile(item,fileKye){
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey : fileKye
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if(errorCode==0){
                        Util.removedarrayitem(this.instructions,item);
                        this.setState({
                            instructions:this.instructions
                        });
                    }
                }
            }
        )
    }
    /*创建成衣订单时的input*/
    gmsInputChange(type,e){
        switch (type){
            case "client":
                this.setState({
                    client:e.target.value
                });
                break;
            case "linkman":
                this.setState({
                    linkman:e.target.value
                });
                break;
            case "contractnum":
                this.setState({
                    contractnum:e.target.value
                });
                break;
        }
    }

    /*制衣厂-成衣订单*/
    handleChange(value) {
        console.log(`selected ${value}`);
    }
    /*保存模板*/
    saveTemplate(){

    }
    /*删除模板*/
    delTemplate(){

    }
    render(){
        const {dataSource_require} = this.state;
        if(this.ispartA){
            if(this.serviceType == 1){
                /*制衣厂-创建成衣订单*/
                return(
                    <div>
                        <Select
                            showSearch
                            style={{ width: 200 }}
                            placeholder="Select a person"
                            optionFilterProp="children"
                            onChange={this.handleChange.bind(this)}
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        >
                            <Option value="jack">Jack</Option>
                            <Option value="lucy">Lucy</Option>
                            <Option value="tom">Tom</Option>
                        </Select>
                        <span className="order_creat_otherRequ_btn">
                            <Button type="primary" className="order_creat_otherRequ_btn_save" onClick={this.saveTemplate.bind(this)}> 保存模板 </Button>
                            <Button type="primary" className="order_creat_otherRequ_btn_del" onClick={this.delTemplate.bind(this)}> 删除模板 </Button>
                        </span>
                        {
                            dataSource_require.map((item,index)=>{
                                return (
                                    <OtherRequirementsItem
                                        item={item}
                                        index={index}
                                        key = {ReactKey.key}
                                    />
                                )
                            })
                        }
                        <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                            <span style={{position: "absolute", top: "0px", left: "60px"}}>备&nbsp;&nbsp;注：</span>
                            <InputBox multiline space={"20"}
                                      style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                        </div>
                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>
                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span className='create_add_contracts' onClick={this.addinstructions.bind(this)}>添加附件</span>
                    </div>
                )
            }else {
                return(
                    <div>
                        {/*<p className="create_order_step">第一步：添加客户信息*/}
                        {/*<span className="create_order_step_line"/>*/}
                        {/*</p>*/}
                        <div>
                            {/*<ul className="create_order_three_ul">*/}
                            {/*<li className="create_order_three_li">*/}
                            {/*<span>客&nbsp;&nbsp;户：</span>*/}
                            {/*<input type='text' ref={'client'}*/}
                            {/*onChange={this.gmsInputChange.bind(this,"client")}*/}
                            {/*value={this.state.traderName}/>*/}
                            {/*</li>*/}
                            {/*<li className="create_order_three_li">*/}
                            {/*<span>联 系 人：</span>*/}
                            {/*<input type='text' ref={'linkman'}*/}
                            {/*onChange={this.gmsInputChange.bind(this,"linkman")}*/}
                            {/*value={this.state.traderUser}/>*/}
                            {/*</li>*/}
                            {/*<li className="create_order_three_li">*/}
                            {/*<span>合同编号：</span>*/}
                            {/*<input type='text' ref={'contractnum'}*/}
                            {/*onChange={this.gmsInputChange.bind(this,"contractnum")}*/}
                            {/*value={this.state.traderId}/>*/}
                            {/*</li>*/}
                            {/*</ul>*/}
                            <DetailUploadModal ref={'deup'} addpact={this.addpact.bind(this)} mid={'stpone'}/>
                            <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                                <span style={{position: "absolute", top: "0px", left: "60px"}}>备&nbsp;&nbsp;注：</span>
                                <InputBox multiline space={"20"}
                                          style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                            </div>
                        </div>
                        {
                            /*  <InputBox style={{width:270,height:27,borderColor:"#36b3b3",paddingRight:"742px",marginTop:"20px"}} titletext={"客户："} ref={'client'}/>
                             <InputBox style={{width:270,height:27,borderColor:"#36b3b3",paddingRight:"742px",marginTop:"20px"}} titletext={"联系人："} ref={'linkman'}/>
                             <InputBox style={{width:270,height:27,borderColor:"#36b3b3",paddingRight:"742px",marginTop:"20px"}} titletext={"合同编号："} ref={'contractnum'}/>
                             <DetailUploadModal ref={'deup'} addpact={this.addpact.bind(this)} mid={'stpone'}/>
                             <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                             <span style={{position: "absolute", top: "0px", left: "100px"}}>备&nbsp;&nbsp;注：</span>
                             <InputBox multiline space={"20"}
                             style={{width: 980, height: 174,paddingRight:"20px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                             </div>*/
                        }

                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>

                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span className='create_add_contracts' onClick={this.addinstructions.bind(this)}>添加附件</span>
                    </div>
                )
            }
        }else{
            if(this.serviceType == 6){
                return(
                    <div>
                        {/*<p className="create_order_step">添加上游订单*/}
                        {/*<span className="create_order_step_line"/>*/}
                        {/*</p>*/}
                        <p style={{width: 1094, height: 58, paddingLeft: "61px",position:"relative",marginTop:"10px"}}>
                            成衣订单：
                            <Select_common
                                className="createorder_stepone_select"
                                oArr={this.state.partAordlist}
                                style={{marginTop:"20px",marginLeft: '1px',width:293,height:27,display:"block",borderColor:"#36b3b3"}}
                                onselectchose={this.choseorder.bind(this)}
                                ref={'partAord'}
                                defaultValue={this.state.fristchose}
                                key={ReactKey.key}
                            />
                            <span style={{position:"absolute",left:"47px",top:"21px",color:"red",display:"block",fontSize:"16px"}}>*</span>
                        </p>
                        <InputBox className="stepone_input1" style={{width:270,height:27,paddingRight:"780px",marginTop:"20px"}} titletext={"供应方："} ref={"partA"} disabled={true} key={ReactKey.key}/>
                        <InputBox className="stepone_input1" style={{width:270,height:27,marginTop:"20px",paddingRight:"780px"}} titletext={"订单金额："} ref={"partacount"} disabled={true}/>


                        <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                            <span style={{position: "absolute", top: "0px", left: "81px"}}>备注：</span>
                            <InputBox multiline space={"20"}
                                      style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                        </div>

                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>

                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span className='create_add_contracts' onClick={this.addinstructions.bind(this)}>添加附件</span>

                    </div>
                )
            }else {
                return(
                    <div>
                        {/*<p className="create_order_step">添加上游订单*/}
                        {/*<span className="create_order_step_line"/>*/}
                        {/*</p>*/}
                        <p style={{width: 1094, height: 58, paddingLeft: "61px",position:"relative",marginTop:"10px"}}>
                            上游订单：
                            <Select_common
                                className="createorder_stepone_select"
                                oArr={this.state.partAordlist}
                                style={{marginTop:"20px",marginLeft: '1px',width:293,height:27,display:"block",borderColor:"#36b3b3"}}
                                onselectchose={this.choseorder.bind(this)}
                                ref={'partAord'}
                                defaultValue={this.state.fristchose}
                                key={ReactKey.key}
                            />
                            <span style={{position:"absolute",left:"47px",top:"21px",color:"red",display:"block",fontSize:"16px"}}>*</span>
                        </p>
                        <InputBox className="stepone_input1" style={{width:270,height:27,paddingRight:"780px",marginTop:"20px"}} titletext={"客户："} ref={"partA"} disabled={true} key={ReactKey.key}/>
                        <InputBox className="stepone_input1" style={{width:270,height:27,marginTop:"20px",paddingRight:"780px"}} titletext={"订单金额："} ref={"partacount"} disabled={true}/>


                        <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                            <span style={{position: "absolute", top: "0px", left: "81px"}}>备注：</span>
                            <InputBox multiline space={"20"}
                                      style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                        </div>

                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>

                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span className='create_add_contracts' onClick={this.addinstructions.bind(this)}>添加附件</span>

                    </div>
                )
            }
        }
    }
}

/**/
class OtherRequirementsItem extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            item: this.props.item,
            othersIds: "",
        };
        this.isSave = true;
    }

    componentWillMount() {

    }

    /*点击保存*/
    save(index) {
        let itemSelf = this.state.item;
        let req = /^(\s)*$/g;

        if (req.test(itemSelf.title) || itemSelf.title.length <= 0) {
            message.warning("标题不能为空");
            return
        }

        if (this.isSave) {
            this.isSave = false;
            let itemStr = JSON.stringify(this.state.item);
            let itemPropsStr = JSON.stringify(this.itemProps);

            /*判断是否修改*/
            if (itemStr == itemPropsStr) {
                /*Relay.Store.commitUpdate(
                    new SaveProOthersDetailMutation({
                        pdId: this.pdId,
                        othersDetail: itemStr,
                    }),
                    {
                        onFailure: (err) => {
                            message.error("网络请求失败")
                        },
                        onSuccess: (res) => {
                            let errorCode = res.saveProOthersDetail.responseData.errorCode;
                            if (errorCode == 0) {
                                let proOthersDetailModel = res.saveProOthersDetail.responseData.proOthersDetailModel;
                                this.props._saveItem(index, proOthersDetailModel.othersId);

                                setTimeout(() => {
                                    this.isSave = true;
                                    message.success("保存成功")
                                }, 300)
                            } else {
                                if (errorCode == 500) {
                                    message.error('服务器错误,请联系系统管理员');
                                }
                            }
                        }
                    }
                );*/
            }
        }
    }


    /*内容编辑*/
    handleTextChange(type, index, e) {
        let itemSelf = this.state.item;
        let text = e.target.value;
        /*限制？？？*/
        if (text.length > 2000)return;
        this.refs[index + type].value = text;
        itemSelf["content"] = text;
        this.setState({
            item: itemSelf,
        })
    }


    render() {
        // const {token, previewVisible, previewImage} = this.state;
        let {title, content} = this.state.item;
        let index = this.props.index;
        return (
            <div className="order_creat_otherReq_item order_creat_otherRequ_edit">
                <p className="order_creat_otherRequ_textp">{title}</p>
                <div className="order_creat_otherRequ_header_text">
                    <Input type="textarea" ref={index + "content"}
                           className="order_creat_otherRequ_textInput"
                           rows={6}
                           value={content} maxlength="500"
                           placeholder="请填写详细要求"
                           onChange={this.handleTextChange.bind(this, "content", index)}
                    />
                </div>
            </div>
        )
    }
}